/****************************************************
	文件：UnityPersistentLog.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2021/1/1 13:46:16
	功能：Unity下的可持久化的Log实现
*****************************************************/

using System;
using System.Collections.Generic;
using System.IO;
using HTFW.Consts;
using HTFW.Core;
using HTFW.Utility.Global;
using UnityEngine;
using IDisposable = HTFW.Core.IDisposable;

namespace HTFW.Logger
{
    public class UnityPersistentLog : IPersistentLog, IDisposable
    {
        Queue<string> mMsgQue;

        public bool Open { get; set; }

        public UnityPersistentLog()
        {
            mMsgQue = new Queue<string>();
            Application.logMessageReceivedThreaded += OnReceiveLogMsg;
            Open = false;
        }

        public void Dispose()
        {
            mMsgQue.Clear();
            Application.logMessageReceivedThreaded -= OnReceiveLogMsg;
            Open = false;
        }

        public void OnReceiveLogMsg(string msg)
        {
            if (msg.IsNullOrEmpty()) return;

            mMsgQue.Enqueue(msg);
        }

        void OnReceiveLogMsg(string condition, string stackTrace, LogType type)
        {
            if (!Open) return;

            string msg = $"[MSG]:{condition}\n[station]:{stackTrace}\n[LogType]:{type.ToString()}";
            OnReceiveLogMsg(msg);
        }

        public void OnLogicUpdate()
        {
            if (!mMsgQue.IsNullOrEmpty())
            {
                LogToFile(mMsgQue.Peek(), true, () => { mMsgQue.Dequeue(); });
            }
        }

        /// <summary>
        /// 日志写入txt
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="writeTime"></param>
        /// <param name="callback"></param>
        void LogToFile(string msg, bool writeTime, Action callback = null)
        {
            if (msg == null) return;
            string path = GetPath();
            try
            {
                using (StreamWriter writer = new StreamWriter(path, true, System.Text.Encoding.UTF8))
                {
                    if (writeTime)
                    {
                        writer.WriteLine("\r\n\r\n---------" + DateTime.Now.ToString());
                    }

                    writer.WriteLine(msg);
                    callback?.Invoke();
                }
            }
            catch
            {
                throw;
            }
        }

        string GetPath()
        {
            return LogDefine.TXT_PERSISTENT_LOG;
        }
    }
}